package Server;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import Command.Command2007;
import OtherFuction.ToHex;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import utils.PropertiesUtils;

/**
 * 数据发送服务线程
 * 
 * @author ack @date Oct 28, 2019
 *
 */
public class Sender extends Thread {

	private static Logger log = LoggerFactory.getLogger(ServerHandler.class);

	String equId;
	byte[] address;
	byte[] dataIdentify;

	public Sender(String equId, byte[] address, byte[] dataIdentify) {
		super();
		this.equId = equId;
		this.address = address;
		this.dataIdentify = dataIdentify;
	}

	@Override
	public void run() {
		log.info("#发送服务线程：[{}]", Thread.currentThread().getName());

		while (1 == 1) {
			ChannelHandlerContext ctx = Server.connectedEquId2Ctx.get(equId);

			byte[] requestData = Command2007.generateRequest(address, Command2007.REQUEST_DATA, 1,
					dataIdentify.clone());
//			log.info("#发送数据-处理前：[{}]", new String(ToHex.ToHex(requestData)));
			// 增加FE激活码
			byte[] newReq = new byte[requestData.length + 4];
			System.arraycopy(new byte[] { (byte) 0xFE, (byte) 0xFE, (byte) 0xFE, (byte) 0xFE }, 0, newReq, 0, 4);
			System.arraycopy(requestData, 0, newReq, 4, requestData.length);
			requestData = newReq;

			try {
//			log.debug("#发送帧数据：[{}]", ToHex.ToHex(requestData));
//			ctx.channel().writeAndFlush(Unpooled.copiedBuffer(requestData));
//			Thread.sleep(300);
				send(ctx, equId, requestData);
			} catch (Exception e) {
				try {
					ctx.close();
					log.info("Connection lost!!");

				} catch (Exception e1) {
					e1.getStackTrace();
				}
			}
			try {
				Thread.sleep(Integer.parseInt(PropertiesUtils.getProperty("collectionInterval", "5000")));
			} catch (Exception e) {
				log.error("#发送线程间歇异常", e);
			}
		}

	}

	@Override
	public void interrupt() {
		App.runningEquIdSet.remove(equId);// 发送线程中断，从发送线程工作集中移除
		log.error("#采集线程[{}]异常中断", Thread.currentThread().getName());
		// TODO 发送线程异常中断，邮件通知
		super.interrupt();
	}

	/**
	 * 初始化电表采集作业，获取电表地址域
	 * 
	 * @author ack @date Oct 29, 2019
	 * @param equId
	 * @param reqData
	 */
	public synchronized static void send(ChannelHandlerContext ctx, String equId, byte[] reqData) {
		if (ctx == null)
			ctx = Server.connectedEquId2Ctx.get(equId);
		try {
			log.debug("#发送帧数据：[{}]", ToHex.ToHex(reqData));
			ctx.channel().writeAndFlush(Unpooled.copiedBuffer(reqData));
			Thread.sleep(Long.parseLong(PropertiesUtils.getProperty("sendFramesInterval", "300")));
		} catch (Exception e) {
			try {
				ctx.close();
				log.info("Connection lost!!");

			} catch (Exception e1) {
				e1.getStackTrace();
			}
		}
	}
}
